package com.usian.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.usian.lister.RabbitMQLister;
import com.usian.mapper.AdUserMapper;
import com.usian.mapper.RegisterMapper;
import com.usian.model.admin.dtos.RegisterDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.service.RegisterService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AdUserMapper adUserMapper;


    @Override
    public ResponseResult register(RegisterDto registerDto) {
        //判断验证码是否超时，redis中是否存在
        String code = stringRedisTemplate.opsForValue().get(registerDto.getPhone());
        /*if(!StringUtils.isEmpty(code)){*/
        //判断输入的验证码是否与redis中的数据一致
        if (code.equals(registerDto.getCode())) {
            AdUser adUser = new AdUser();
            BeanUtils.copyProperties(registerDto, adUser);
            adUser.setUsername(registerDto.getPhone());
            int c = RandomUtil.randomInt(1000, 9999);
            adUser.setSalt(c + "");
            String pswd = registerDto.getPhone() + c + "";
            String saltPswd = DigestUtils.md5DigestAsHex(pswd.getBytes());
            adUser.setPassword(saltPswd);
            adUser.setStatus(2);
            //注册
            adUserMapper.insert(adUser);
            return ResponseResult.okResult(0, "注册成功");
        } else {
            return ResponseResult.errorResult(301, "验证码输入错误");
        }

    /*else{
            return ResponseResult.errorResult(300,"验证码已过期");
        }*/
    }


    @Override
    public ResponseResult sendCode(String phone) {
        AdUser adUser = registerMapper.findUserByPhone(phone);
        if(adUser == null){
            RabbitMQLister rabbitMQLister = new RabbitMQLister();
            //调用阿里大鱼发送短信
            rabbitTemplate.convertAndSend("direct.exchange","pian",phone);
            rabbitMQLister.sendCode(phone);
            return ResponseResult.okResult("注册成功");
        }else {
            return ResponseResult.errorResult(300,"手机号已注册");
        }

    }

    @Override
    public AdUser findUserByPhone(String phone) {
        AdUser adUser = registerMapper.findUserByPhone(phone);
        return adUser;
    }
/*13352553382**/
}
